package model

import (
	"errors"
	"fmt"
	"github.com/jinzhu/gorm"
	"kubeInstall/utils"
)

type PkgInfo struct {
	SysPackage  []SysPackage  `json:"sys_package"`
	DockerImage []DockerImage `json:"docker_image"`
}

type SysPackage struct {
	ID      string `json:"id" gorm:"primary_key;column:package_id"`
	Name    string `json:"name" gorm:"unique;not null"`
	Size    int64  `json:"size"`
	Version string `json:"version"`
	Comment string `json:"comment"`
	BaseModel
}

func (sysPkg *SysPackage) Get(packageId string) (SysPackage, error) {
	var sysPackage SysPackage
	err := db.Where("package_id = ?", packageId).First(&sysPackage).Error

	if err != nil {
		return sysPackage, err
	}

	return sysPackage, nil
}

func (sysPkg *SysPackage) GetSysPackages() ([]*SysPackage, error) {
	var pkgs []*SysPackage

	err := db.Find(&pkgs).Error

	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return pkgs, nil

}

func (sysPkg *SysPackage) Delete(imageId string) error {
	var sysPackage SysPackage
	err := db.Where("package_id = ?", imageId).Delete(&sysPackage).Error

	return err
}

func (sysPkg *SysPackage) Create() (SysPackage, error) {
	//判断文件是否存在
	var count int

	db.Model(SysPackage{}).Where("name = ?&& size = ?", sysPkg.Name, sysPkg.Size).Count(&count)
	if count > 1 {
		return SysPackage{}, errors.New(fmt.Sprintf("system package: %s already exsist", sysPkg.Name))
	}

	//插入数据，并返回。
	sysPkg.ID = utils.GenUUID()
	if err := db.Create(&sysPkg).Error; err != nil {
		return SysPackage{}, err
	}
	return *sysPkg, nil
}
